﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SG.SDK.Configuration;
using SG.SDK;
using System.Configuration;
using DataIssue.Entity;

namespace DataIssue.Service
{
    /// <summary>
    /// 行情快照
    /// </summary>
    public class SnapSingleton
    {
        //获取行情快照数据Thread
        private static Thread snapThread = new Thread(new ParameterizedThreadStart(GetSnapData));
        //访问实例锁
        private static Object instanceLockObject = new Object();
        //访问快照锁
        private static Object snakLockObject = new Object();
        //快照列表
        private static List<QuoteSnap> snapList;
        //实例
        private static SnapSingleton instance;
        //获取SG服务器地址
        private static string sgSDKServerAddress = ConfigurationSettings.AppSettings["SGSDKServerAddress"];
        //获取G服务器端口
        private static int sgSDKServerPort =Int32.Parse(ConfigurationSettings.AppSettings["SGSDKServerPort"]);


        private SnapSingleton()
        {

        }

        #region 实例
        /// <summary>
        /// 实例
        /// </summary>
        public static SnapSingleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (instanceLockObject)
                    {
                        if (instance == null)
                            instance = CreateInstance();
                    }
                }

                return instance;
            }
        }
        #endregion

        #region 创建实例
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <returns></returns>
        private static SnapSingleton CreateInstance()
        {
            return new SnapSingleton();
        }
        #endregion

        #region 启动
        /// <summary>
        /// 启动
        /// </summary>
        public static void Start()
        {
            snapThread.Start();
        }
        #endregion

        #region 获取快照数据
        /// <summary>
        /// 获取快照数据
        /// </summary>
        /// <param name="obj"></param>
        private static void GetSnapData(object obj)
        {
            while (true)
            {
                if (NeedRefresh())
                {
                    if (snapList == null || snapList.Count == 0)
                    {
                        snapList = GetSnapList();
                    }
                    else
                    {
                        List<QuoteSnap> newSnapList = GetSnapList();
                        if (newSnapList != null && newSnapList.Count > 0)
                        {
                            snapList = newSnapList;
                        }
                    }
                }

                Thread.Sleep(600000);
            }
        }
        #endregion

        #region 获取快照列表
        /// <summary>
        /// 获取快照列表
        /// </summary>
        /// <returns></returns>
        private static List<QuoteSnap> GetSnapList()
        {
            List<QuoteSnap> dataList = new List<QuoteSnap>();
            try
            {

                SDKClient client = new SDKClient(new ResourceAddress(sgSDKServerAddress, sgSDKServerPort), "FEED_HS_QUOTESNAP");

                client.SetFull(2);
                //获取数据

                SGObject[] array = client.GetRows();
                if (array != null)
                {
                    foreach (SGObject data in array)
                    {
                        QuoteSnap quoteSnap = new QuoteSnap();
                        //证券代码
                        quoteSnap.Code = data["STOCKCODE"].ToString();
                        //证券简称
                        quoteSnap.Name = data["SHORT_NAME"].ToString();
                        //市场类型
                        quoteSnap.MarketType = data["MARKETTYPE"].NullIntValue();
                        //证券类型
                        quoteSnap.SecurtyType = data["TYPE"].NullIntValue();
                        //所属行业
                        quoteSnap.Industry = data["INDUSTRY"].ToString();
                        //行业代码
                        quoteSnap.IndustryCode = data["INDUSTRY_CODE"].ToString();
                        //概念板块
                        quoteSnap.ConceptPlate = data["CONCEPT"].ToString();
                        //概念板块代码
                        quoteSnap.ConceptPlateCode = data["CONCEPT_CODE"].NullIntValue();
                        //地域
                        quoteSnap.Region = data["REGION"].ToString();
                        //地域代码
                        quoteSnap.RegionCode = data["REGION_CODE"].NullIntValue();
                        //涨跌额
                        quoteSnap.UpDownValue = data["CALC"]["PXCHG"].NullDoubuleValue();
                        //涨跌幅
                        quoteSnap.UpDownRate = data["CALC"]["PXCHGRATIO"].NullDoubuleValue();
                        //1分钟涨跌幅
                        quoteSnap.OneMinUpDownRate = data["CALC"]["PXCHGRATIOIN1MIN"].NullDoubuleValue();
                        //3分钟涨跌幅
                        quoteSnap.ThreeMinUpDownRate = data["CALC"]["PXCHGRATIOIN3MIN"].NullDoubuleValue();
                        //5分钟涨跌幅
                        quoteSnap.FiveMinUpDownRate = data["CALC"]["PXCHGRATIOIN5MIN"].NullDoubuleValue();
                        //昨收
                        quoteSnap.PreClosePrice = data["PRECLOSEPX"].NullDoubuleValue();
                        //开盘价
                        quoteSnap.OpenPrice = data["OPENPX"].NullDoubuleValue();
                        //最高价
                        quoteSnap.HightPrice = data["HIGHPX"].NullDoubuleValue();
                        //最低价
                        quoteSnap.LowestPrice = data["LOWPX"].NullDoubuleValue();
                        //当前价格
                        quoteSnap.CurrentPrice = data["LASTPX"].NullDoubuleValue();
                        //成交量
                        quoteSnap.Volume = data["VOLUME"].NullLongValue();
                        //内盘成交量
                        quoteSnap.InnerVolume = data["CALC"]["INNERVOLUME"].NullLongValue();
                        //外盘成交量
                        quoteSnap.OuterVolume = data["CALC"]["OUTERVOLUME"].NullLongValue();
                        //成交金额
                        quoteSnap.Amount = data["VALUE"].NullLongValue();
                        //成交笔数
                        quoteSnap.TradeNumber = data["TRADENUM"].NullIntValue();
                        //总委买量
                        quoteSnap.TotalBuyCommission = data["TOTALBIDVOLUME"].NullLongValue();
                        //总委卖量
                        quoteSnap.TotalSellCommission = data["TOTALOFFERVOLUME"].NullLongValue();
                        //振幅
                        quoteSnap.Amplitude = data["CALC"]["PXAMPLITUDE"].NullDoubuleValue();
                        //市盈率
                        quoteSnap.Peratio = data["PERATIO1"].NullDoubuleValue();
                        //换手率
                        quoteSnap.TurnOver = data["CALC"]["TURNOVER"].NullDoubuleValue();
                        //委比
                        quoteSnap.CommissionRate = data["CALC"]["WEIBI"].NullDoubuleValue();
                        //量比
                        quoteSnap.VolumeRate = data["CALC"]["LIANGBI"].NullDoubuleValue();
                        //交易时间
                        quoteSnap.TradeDate = data["TRADEDATE"].NullIntValue();
                        //停牌状态
                        quoteSnap.HaltState = data["STOPSTATE"].NullIntValue();
                        //指数分类
                        quoteSnap.IndexCategory = data["SECTION_CODE"].ToString();
                        //快照时间
                        quoteSnap.SnapTime = data["SNAPTIME"].NullIntValue();
                        //上市状态
                        quoteSnap.ListedState = data["LIST_STATUS"].NullIntValue();

                        //买入明细
                        if (data["BIDDETAILS"] != null)
                        {
                            SGObject[] buyArray = data["BIDDETAILS"].Children();

                            if (buyArray != null && buyArray.Length > 0)
                            {
                                quoteSnap.BuyDetail = new List<TradeDetail>();
                                foreach (SGObject buyData in buyArray)
                                {
                                    TradeDetail tradeDetail = new TradeDetail();
                                    //索引
                                    tradeDetail.Index = buyData["INDEX"].IntValue();
                                    //交易价格
                                    tradeDetail.Price = buyData["PRICE"].NullDoubuleValue();
                                    //成交量
                                    tradeDetail.Volume = buyData["VOLUME"].NullIntValue();

                                    quoteSnap.BuyDetail.Add(tradeDetail);
                                }
                            }
                        }
                        //卖出明细
                        if (data["ASKDETAILS"] != null)
                        {
                            SGObject[] sellArray = data["ASKDETAILS"].Children();

                            if (sellArray != null && sellArray.Length > 0)
                            {
                                quoteSnap.SellDetail = new List<TradeDetail>();
                                foreach (SGObject sellData in sellArray)
                                {
                                    TradeDetail tradeDetail = new TradeDetail();
                                    //索引
                                    tradeDetail.Index = sellData["INDEX"].IntValue();
                                    //交易价格
                                    tradeDetail.Price = sellData["PRICE"].NullDoubuleValue();
                                    //成交量
                                    tradeDetail.Volume = sellData["VOLUME"].NullIntValue();

                                    quoteSnap.SellDetail.Add(tradeDetail);
                                }
                            }
                        }


                        dataList.Add(quoteSnap);
                    }
                }


                //int count = dataList != null ? dataList.Count : 0;
                //logger.Info(String.Format("更新快照成功！数据个数{0}", count));
            }

            catch (Exception ex)
            {
                return null;
            }

            return dataList;

        }
        #endregion

        #region 是否需要更新
        private static bool NeedRefresh()
        {
            bool needRefresh = false;

            DateTime nowTime = DateTime.Now;
            DateTime beginTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 8, 50, 0);
            DateTime endTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 15, 30, 0);
            if (nowTime.CompareTo(beginTime) >= 0 && nowTime.CompareTo(endTime) <= 0)
                needRefresh = true;

            return needRefresh;
        }
        #endregion

        #region 快照列表
        /// <summary>
        /// 快照列表
        /// </summary>
        public List<QuoteSnap> SnapList
        {
            get
            {
                if (snapList == null || snapList.Count == 0)
                {
                    lock (snakLockObject)
                    {
                        if (snapList == null || snapList.Count == 0)
                            snapList = GetSnapList();
                    }
                }
                return snapList;
            }
        }
        #endregion
    }

}
